package com.offer;

/**
 * @Author: huangzhigao
 * @Date: 2023/3/4 16:42
 */
public class offer12 {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        int row = board.length;
        int col = board[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (dfs(board, i, j, words, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(char[][] board, int row, int col, char[] word, int index) {
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || word[index] != board[row][col]) {
            return false;
        }
        if (index == word.length - 1) {
            return true;
        }
        board[row][col] = '\0';
        boolean res = dfs(board, row + 1, col, word, index + 1) || dfs(board, row - 1, col, word, index + 1)
                || dfs(board, row, col + 1, word, index + 1) || dfs(board, row, col - 1, word, index + 1);
        board[row][col] = word[index];
        return res;
    }
}
